<?php
require_once('wpfunctions.php');
header("Content-type: application/json");
$root = 'verses/';
$term = $_REQUEST['term'];
$initial = substr($term,0,1);
if($initial == '|') {
  $term = substr($term,1);
} else {
  $initial = '';
}

$dirs = ip_allFiles($root . $term);
$result = array();
foreach ($dirs as $i => $dir) {
  $index = strrpos($dir, '/');
  $beginning = substr($dir,$index + 1);
  $dir = substr($dir,0,$index);

  $index = strrpos($term, '/');
  if($index === false) {
    $termbeginning = $initial;
    if(is_dir($dir)) {
      $entries = ip_scandir($dir);
      foreach($entries as $v) {
        if(substr($v, 0, strlen($beginning)) == $beginning) {
          if(is_dir("$dir/$v") && !preg_match('/^\.|^(?:~|\.{1,2})$/',$v)) {
              $result[] = $termbeginning . $v;
          }
        }
      }
    }
  }
}
echo json_encode(array_unique($result));
?>